﻿@inject IUserStatusService userStatusService
@inject IRescanService rescanService

<MudDialog>
    <DialogContent>
        @if( AllImages )
        {
            <MudText>Re-scan ALL folders.</MudText>
            <MudText>WARNING: this may take hours or days, depending on how many images are in your library.</MudText>
        }
        else if( Folder != null )
        {
            <MudText>Re-scan folder @Folder.Name (@ImageText):</MudText>
        }
        else
        {
            <MudText>Re-scan @ImageText:</MudText>
        }
        <div>
            <MudCheckBox @bind-Value="@ReIndex" Label="Re-index image files"/>
        </div>
        <div>
            <MudCheckBox @bind-Value="@RescanMetadata" Label="Re-scan metadata"/>
        </div>
        <div>
            <MudCheckBox @bind-Value="@RegenThumbs" Label="Re-generate thumbnails"/>
        </div>
        <div>
            <MudCheckBox @bind-Value="@RescanAI" Label="Re-scan for AI objects"/>
        </div>
    </DialogContent>
    <DialogActions>
        <MudButton OnClick="Cancel">Cancel</MudButton>
        <MudButton Color="Color.Primary" OnClick="OkayClicked">Rescan</MudButton>
    </DialogActions>
</MudDialog>

@code {

    [CascadingParameter] MudDialogInstance MudDialog { get; set; }

    [Parameter] public ICollection<Image> Images { get; set; }

    [Parameter] public Folder Folder { get; set; }

    [Parameter] public bool AllImages { get; set; }

    [Parameter] public int Count { get; set; }

    private string ImageText => Count > 1 ? $"{Count} images" : "1 image";

    private bool ReIndex { get; set; }
    private bool RegenThumbs { get; set; }
    private bool RescanAI { get; set; }
    private bool RescanMetadata { get; set; }

    void OkayClicked()
    {
        MudDialog.Close(DialogResult.Ok(true));

        // Fire and forget; we don't need to block/await
        _ = Rescan();
    }

    private async Task Rescan()
    {
        var scanType = RescanTypes.None;
        if( ReIndex )
            scanType |= RescanTypes.Indexing;
        if( RescanMetadata )
            scanType |= RescanTypes.Metadata;
        if( RegenThumbs )
            scanType |= RescanTypes.Thumbnails;
        if( RescanAI )
            scanType |= RescanTypes.AI;
        if( AllImages )
        {
            await rescanService.MarkAllForRescan(scanType);
        }
        else if( Folder == null )
        {
            await rescanService.MarkImagesForRescan(scanType, Images.Select(x => x.ImageId).ToList());
        }
        else
        {
            await rescanService.MarkFolderForRescan(scanType, Folder.FolderId);
        }
    }

    void Cancel()
    {
        MudDialog.Cancel();
    }

    protected override async Task OnInitializedAsync()
    {
        if( Images != null )
            Count = Images.Count;

        await base.OnInitializedAsync();
    }

}